package com.efounder.frame.fragment;

import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;

import android.view.ViewGroup;

import com.core.xml.StubObject;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.frame.utils.EFFrameUtils;
import com.efounder.frame.utils.EFViewTypeUtils;
import com.efounder.frame.xmlparse.EFXmlConstants;
import com.efounder.util.AbFragmentManager;

import java.io.Serializable;
import java.util.List;

/**
 * Created by hudq on 2016/8/20.
 */

public class EFAppAccountPagerSlidingTabFragmentPagerAdapter extends FragmentPagerAdapter {//FragmentStatePagerAdapter FragmentPagerAdapter

    private List<StubObject> dataList;
    private Fragment currentFragment;

    public EFAppAccountPagerSlidingTabFragmentPagerAdapter(FragmentManager fragmentManager, List<StubObject> dataList) {
        super(fragmentManager);
        this.dataList = dataList;
    }

    @Override
    public void setPrimaryItem(ViewGroup container, int position, Object object) {
        currentFragment = (Fragment) object;
        super.setPrimaryItem(container, position, object);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return dataList.get(position).getString(EFXmlConstants.ATTR_CAPTION,"");
    }

    @Override
    public int getCount() {
        return dataList.size();
    }

    @Override
    public Fragment getItem(int position) {
        //TODO 根据ViewType获取Fragment
        StubObject stubObject = dataList.get(position);
        String viewType = stubObject.getString(EFXmlConstants.ATTR_VIEW_TYPE,"");
        String androidShow = stubObject.getString("AndroidShow","");
        Fragment fragment = null;
        if (!"".equals(androidShow.trim())) {
            AbFragmentManager abFragmentManager = new AbFragmentManager(EFFrameUtils.getCurrentActivity());
            fragment = abFragmentManager.getFragment(stubObject);
        }else if (!"".equals(viewType.trim())){
            fragment = EFViewTypeUtils.getFragment(viewType);
        }else{
            fragment = new EFDefaultFragment();
        }
        //FIXME fragment绑定数据
        Bundle bundle = new Bundle();
        bundle.putInt("position", position);
//        bundle.putSerializable("stubObject",stubObject);
        bundle.putSerializable("stubList", (Serializable) dataList);
        fragment.setArguments(bundle);
        if(fragment instanceof  BaseFragment){
            ((BaseFragment)fragment).setAlone(false);
        }
        return fragment;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        return super.instantiateItem(container, position);
    }

    public Fragment getCurrentFragment() {
        return currentFragment;
    }
}